package in.indijava.scjp5questions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Comparable_CompareTo {

	public static void main(String[] args) {
		List<Anything> list = new ArrayList<Anything>();
		list.add(new Anything(5));
		list.add(new Anything(25));
		list.add(new Anything(15));
		list.add(new Anything(85));
		list.add(new Anything(45));
		list.add(new Anything(10));
		
		System.out.println("BEFORE: " + list);
		Collections.sort(list);
		System.out.println("AFTER: " + list);
		
		list = new ArrayList<Anything>();
		list.add(new Anything(5));
		list.add(new Anything(25));
		list.add(new Anything(15));
		list.add(new Anything(85));
		list.add(new Anything(45));
		list.add(new Anything(10));
		
		System.out.println("BEFORE: " + list);
		Collections.sort(list, new AnyComparator2());
		System.out.println("AFTER: " + list);
	}
	
	static class Anything implements Comparable<Anything> {

		private int value;
		
		public Anything(int value) {
			this.value = value;
		}
		
		public int getValue() {
			return value;
		}
		
		@Override
		public String toString() {
			return "Anything[" + value + "]";
		}
		
		@Override
		public int compareTo(Anything o) {
			if (o != null) {
				if (o.value < this.value) {
					return 1;
				}
				else {
					return -1;
				}
			}
			else {
				return 1;
			}
		}
		
	}
	
	static class AnyComparator implements Comparator<Anything> {

		@Override
		public int compare(Anything o1, Anything o2) {
			if (o1 != null && o2 != null) {
				if (o1.getValue() > o2.getValue()) {
					return 1;
				}
				else {
					return -1;
				}
			}
			else {
				return -1;
			}
		}
		
	}
	
	static class AnyComparator2 implements Comparator<Anything> {

		@Override
		public int compare(Anything o1, Anything o2) {
			return o1.compareTo(o2);
		}
		
	}
	
}
